<!-- src/views/admin/UsersList.vue -->
<template>
  <div class="users-page">
    <el-card class="page-card" :body-style="{ padding: '20px' }">
      <!-- 页面标题 -->
      <div class="page-header">
        <h2 class="page-title">用户管理</h2>
        <p class="page-subtitle">管理系统用户账号和权限</p>
      </div>

      <!-- 工具栏 -->
      <div class="toolbar">
        <div class="toolbar-left">
          <el-input
            v-model="filters.username"
            placeholder="搜索用户名"
            clearable
            @clear="onSearch"
            @keyup.enter="onSearch"
            class="toolbar-search"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </div>
        <div class="toolbar-actions">
          <el-tooltip content="新增用户" effect="dark" placement="top">
            <el-button type="primary" circle @click="openDialog()" class="action-button">
              <el-icon><Plus /></el-icon>
            </el-button>
          </el-tooltip>
          <el-tooltip content="批量删除" effect="dark" placement="top">
            <el-button
              type="danger"
              circle
              :disabled="!multipleSelection.length"
              @click="onBatchDelete"
              class="action-button"
            >
              <el-icon><Delete /></el-icon>
            </el-button>
          </el-tooltip>
        </div>
      </div>

      <!-- 用户表格 -->
      <el-table
        v-loading="loading"
        :data="users"
        stripe
        highlight-current-row
        @selection-change="onSelectChange"
        class="users-table"
      >
        <el-table-column type="selection" width="50" />
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="username" label="用户名" min-width="120">
          <template #default="{ row }">
            <div class="user-info">
              <el-avatar :size="32" class="user-avatar">{{ row.username.charAt(0).toUpperCase() }}</el-avatar>
              <span class="username">{{ row.username }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="nickname" label="昵称" min-width="120" />
        <el-table-column prop="phone" label="手机号" min-width="140" />
        <el-table-column prop="email" label="邮箱" min-width="180" />
        <el-table-column prop="createdAt" label="创建时间" width="180" />
        <el-table-column prop="updatedAt" label="更新时间" width="180" />

        <el-table-column label="操作" width="120" fixed="right">
          <template #default="{ row }">
            <div class="row-actions">
              <el-tooltip content="编辑" effect="dark" placement="top">
                <el-button
                  type="primary"
                  :icon="Edit"
                  circle
                  plain
                  @click="openDialog(row)"
                  class="action-button"
                />
              </el-tooltip>
              <el-tooltip content="删除" effect="dark" placement="top">
                <el-button
                  type="danger"
                  :icon="Delete"
                  plain
                  circle
                  @click="onDelete(row)"
                  class="action-button"
                />
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          background
          layout="prev, pager, next, jumper, sizes, total"
          :page-size="pageSize"
          :current-page="pageNum"
          :page-sizes="[10, 20, 50]"
          :total="total"
          @current-change="onPageChange"
          @size-change="onSizeChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑 弹窗 -->
    <el-dialog 
      :title="dialogTitle" 
      v-model="dialogVisible" 
      width="500px"
      destroy-on-close
      class="user-dialog"
    >
      <el-form 
        :model="form" 
        :rules="rules" 
        ref="formRef" 
        label-width="100px"
        class="user-form"
      >
        <el-form-item label="用户名" prop="username">
          <el-input 
            v-model="form.username" 
            autocomplete="off"
            placeholder="请输入用户名"
          />
        </el-form-item>
        <el-form-item v-if="isCreate" label="密码" prop="password">
          <el-input
            v-model="form.password"
            type="password"
            autocomplete="new-password"
            placeholder="请输入密码"
            show-password
          />
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input 
            v-model="form.nickname" 
            autocomplete="off"
            placeholder="请输入昵称"
          />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input 
            v-model="form.phone" 
            autocomplete="off"
            placeholder="请输入手机号"
          />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input 
            v-model="form.email" 
            autocomplete="off"
            placeholder="请输入邮箱"
          />
        </el-form-item>
        <el-form-item label="角色" prop="roleIds">
          <el-select 
            v-model="form.roleIds" 
            multiple 
            placeholder="请选择角色"
            class="role-select"
          >
            <el-option
              v-for="r in allRoles"
              :key="r.id"
              :label="r.name"
              :value="r.id"
            />
          </el-select>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm" :loading="dialogLoading">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  pageUsers,
  getUser,
  createUser,
  updateUser,
  deleteUsers,
} from "@/api/users";
import { Search, Plus, Delete, Edit } from "@element-plus/icons-vue";

// —— 列表分页状态 ——
const loading = ref(false);
const users = ref([]);
const total = ref(0);
const pageNum = ref(1);
const pageSize = ref(10);
const filters = ref({ username: "" });
const multipleSelection = ref([]);
const editingId = ref(null);

function fetchList() {
  loading.value = true;
  pageUsers({
    pageNum: pageNum.value,
    pageSize: pageSize.value,
    username: filters.value.username,
  })
    .then((res) => {
      const data = res.data;
      users.value = data.items;
      total.value = data.total;
    })
    .finally(() => (loading.value = false));
}

// 分页回调
function onPageChange(page) {
  pageNum.value = page;
  fetchList();
}
function onSizeChange(size) {
  pageSize.value = size;
  pageNum.value = 1;
  fetchList();
}

// 搜索
function onSearch() {
  pageNum.value = 1;
  fetchList();
}

// 选择框
function onSelectChange(val) {
  multipleSelection.value = val;
}

// 单条删除
function onDelete(row) {
  ElMessageBox.confirm("确认删除该用户？", "提示", { type: "warning" })
    .then(() => {
      return deleteUsers([row.id].join(","));
    })
    .then(() => {
      ElMessage.success("删除成功");
      fetchList();
    });
}

// 批量删除
function onBatchDelete() {
  const ids = multipleSelection.value.map((i) => i.id);
  ElMessageBox.confirm(`确认删除选中的 ${ids.length} 条？`, "提示", {
    type: "warning",
  })
    .then(() => {
      return deleteUsers(ids.join(","));
    })
    .then(() => {
      ElMessage.success("批量删除成功");
      multipleSelection.value = [];
      fetchList();
    });
}

// —— 新增/编辑 弹窗 ——
const dialogVisible = ref(false);
const isCreate = ref(true);
const dialogTitle = ref("新增用户");
const form = ref({
  username: "",
  password: "",
  nickname: "",
  phone: "",
  email: "",
  roleIds: [],
});
const formRef = ref(null);
const dialogLoading = ref(false);

// 验证规则
const rules = {
  username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
  password: [
    { required: () => isCreate.value, message: "请输入密码", trigger: "blur" },
    { min: 6, message: "密码至少 6 位", trigger: "blur" },
  ],
  nickname: [{ max: 50, message: "昵称最多 50 字", trigger: "blur" }],
  phone: [
    { pattern: /^\d{10,15}$/, message: "请输入正确手机号", trigger: "blur" },
  ],
  email: [{ type: "email", message: "请输入正确邮箱", trigger: "blur" }],
  roleIds: [
    { type: "array", required: true, message: "请选择角色", trigger: "change" },
  ],
};

const allRoles = ref([
  { id: 1, name: "admin" },
  { id: 17, name: "auditor" },
  { id: 11, name: "user" },
]);

function openDialog(row) {
  if (row) {
    isCreate.value = false;
    editingId.value = row.id;
    dialogTitle.value = "编辑用户";
    getUser(row.id).then((res) => {
      const d = res.data;

      const nameToId = allRoles.value.reduce((map, r) => {
        map[r.name] = r.id;
        return map;
      }, {});

      const mappedIds = (d.roles || [])
        .map((name) => nameToId[name])
        .filter((id) => id != null);

      form.value = {
        username: d.username,
        nickname: d.nickname,
        phone: d.phone,
        email: d.email,
        roleIds: mappedIds,
      };
      dialogVisible.value = true;
    });
  } else {
    // 新增逻辑
    isCreate.value = true;
    editingId.value = null;
    dialogTitle.value = "新增用户";
    form.value = {
      username: "",
      password: "",
      nickname: "",
      phone: "",
      email: "",
      roleIds: [],
    };
    dialogVisible.value = true;
  }
}

// 提交表单
function submitForm() {
  formRef.value.validate((valid) => {
    if (!valid) return;
    dialogLoading.value = true;

    const payload = { ...form.value };
    let request;
    if (isCreate.value) {
      request = createUser(payload);
    } else {
      request = updateUser(editingId.value, payload);
    }

    request
      .then(() => {
        ElMessage.success(isCreate.value ? "新增成功" : "更新成功");
        dialogVisible.value = false;
        fetchList();
      })
      .finally(() => (dialogLoading.value = false));
  });
}

// 初始加载
onMounted(fetchList);
</script>

<style scoped>
.users-page {
  width: 100%;
  min-height: 100%;
  background-color: #f5f7fa;
  padding: 20px;
}

.page-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
}

.page-card:hover {
  box-shadow: 0 4px 16px 0 rgba(0, 0, 0, 0.1);
}

.page-header {
  margin-bottom: 24px;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 8px 0;
}

.page-subtitle {
  font-size: 14px;
  color: #909399;
  margin: 0;
}

/* 工具栏样式 */
.toolbar {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  gap: 16px;
}

.toolbar-left {
  display: flex;
  gap: 16px;
  flex: 1;
}

.toolbar-search {
  width: 300px;
}

.toolbar-search :deep(.el-input__wrapper) {
  box-shadow: 0 0 0 1px #dcdfe6 inset;
  transition: all 0.3s ease;
}

.toolbar-search :deep(.el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px #409eff inset;
}

.toolbar-actions {
  display: flex;
  gap: 12px;
}

.action-button {
  transition: all 0.3s ease;
}

.action-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 表格样式 */
.users-table {
  margin: 16px 0;
  border-radius: 8px;
  overflow: hidden;
}

.users-table :deep(.el-table__header) {
  background-color: #f5f7fa;
}

.users-table :deep(.el-table__row) {
  transition: all 0.3s ease;
}

.users-table :deep(.el-table__row:hover) {
  background-color: #f5f7fa !important;
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.user-avatar {
  background-color: #409eff;
  color: white;
  font-weight: 500;
}

.username {
  font-weight: 500;
  color: #303133;
}

.row-actions {
  display: flex;
  gap: 8px;
  opacity: 0.6;
  transition: all 0.3s ease;
}

.el-table__row:hover .row-actions {
  opacity: 1;
}

/* 分页样式 */
.pagination {
  padding-top: 20px;
  text-align: right;
}

/* 弹窗样式 */
.user-dialog :deep(.el-dialog__header) {
  margin: 0;
  padding: 20px;
  border-bottom: 1px solid #e4e7ed;
}

.user-dialog :deep(.el-dialog__title) {
  font-size: 18px;
  font-weight: 600;
}

.user-form {
  padding: 20px 0;
}

.user-form :deep(.el-form-item__label) {
  font-weight: 500;
}

.role-select {
  width: 100%;
}

.dialog-footer {
  padding: 20px;
  border-top: 1px solid #e4e7ed;
  text-align: right;
}

/* 响应式调整 */
@media screen and (max-width: 768px) {
  .users-page {
    padding: 12px;
  }

  .toolbar {
    flex-direction: column;
    align-items: stretch;
  }

  .toolbar-left {
    flex-direction: column;
  }

  .toolbar-search {
    width: 100%;
  }

  .toolbar-actions {
    justify-content: flex-end;
  }

  .page-title {
    font-size: 20px;
  }
}

/* 动画效果 */
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.page-card {
  animation: fadeIn 0.3s ease-out;
}

.el-table__row {
  animation: fadeIn 0.3s ease-out;
}
</style>
  